module("framework.core.pool.LuaObjPool",package.seeall)

---@class LuaObjPool
local LuaObjPool = class("LuaObjPool")

---ctor
---@param maxCount number
---@param newFunc fun()
---@param releaseFunc fun(obj:any)
---@param resetFunc fun(obj:any)
function LuaObjPool:ctor(maxCount, newFunc, releaseFunc, resetFunc)
    self._maxCount = maxCount
    self._newFunc = newFunc
    self._releaseFunc = releaseFunc
    self._resetFunc = resetFunc

    if nil == maxCount or nil == newFunc or nil == releaseFunc or nil == resetFunc then
        logError("LuaObjPool, 对象池构造，所有参数都不能为nil")
    end
    if self._maxCount == 0 then
        self._maxCount = 32
    end
    self._cacheList = {}
end

--获取新对象
function LuaObjPool:getObject()
    local curCount = #self._cacheList
    if curCount < 1 then
        return self._newFunc()
    else
        return table.remove(self._cacheList)
    end
end

--回收不用的对象
--超过最大容量，则直接销毁
function LuaObjPool:putObject(luaObj)
    local curCount = #self._cacheList
    self._resetFunc(luaObj)
    if curCount >= self._maxCount then
        self._releaseFunc(luaObj)
    else
        if not tabletool.indexOf(self._cacheList, luaObj) then
            table.insert(self._cacheList, luaObj)
        end
    end
end

--清空这个对象池
function LuaObjPool:dispose()
    local curCount = #self._cacheList
    if curCount == 0 then
        return 
    end
    local luaObj = nil
    for idx = 1, curCount do
        luaObj = self._cacheList[idx]
        self._releaseFunc(luaObj)
        self._cacheList[idx] = nil
    end
end

return LuaObjPool
